<template>
  <CDialog
    :title="title"
    :close-on-click-modal="false"
    v-model:visible="dialogVisible"
    size="default"
    @cancel="handleClose"
    @confirm="handleConfirm"
    confirm-text="保存"
  >
    <div class="form-dialog-container" v-loading="loading">
      <el-form ref="formRef" :model="formData" :rules="rules" label-position="top">
        <el-row :gutter="20">
          <el-col :span="16">
            <el-form-item label="排放单位" prop="organizationCode">
              <CSelect
                v-model="formData.organizationCode"
                placeholder="请选择"
                @change="handChange"
                :disabled="isEdit"
              >
                <el-option
                  v-for="item in props.dischargeUnitOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </CSelect>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="年份" prop="dischargeYear">
              <el-date-picker
                type="year"
                format="YYYY"
                value-format="YYYY"
                v-model="formData.dischargeYear"
                placeholder="请输入"
                clearable
                :disabled="isEdit"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="组织边界" prop="organizationBoundary">
              <CSelect
                v-model="formData.organizationBoundary"
                multiple
                placeholder="请选择"
                :disabled="!formData.organizationCode"
              >
                <el-option
                  v-for="item in organizationBoundarOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </CSelect>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </CDialog>
</template>
<script lang="ts" setup name="AddOrEditLowCarbonMaterial">
import { defineProps, withDefaults, defineEmits, computed, ref, watch, reactive } from 'vue';
import { CDialog } from '@/components/CDialog';
import { CSelect } from '@/components/CSelect';
import type { GetInspectListResult } from '@/apis/taa/asset/model/inspectModel';
import {
  postCreateCarbonInspect,
  postEditCarbonInspect
  // getChildByCodeList
} from '@/apis/taa/asset/inspect';
import { getChildFactoryOrg } from '@/apis/system/organization';
import { useMessage } from '@/hooks/useMessage';

import { rules } from './rules';

interface CSetEmissionFactorDialogProps {
  visible: boolean;
  tempRow?: GetInspectListResult;
  // eslint-disable-next-line no-undef
  dischargeUnitOption: LabelValueOptions;
}
const props = withDefaults(defineProps<CSetEmissionFactorDialogProps>(), {});
const emits = defineEmits(['update:visible', 'refresh']);
const { createMessage } = useMessage();
const dialogVisible = computed<boolean>({
  get: () => {
    return props.visible;
  },
  set: val => {
    emits('update:visible', val);
  }
});

watch(
  () => props.visible,
  val => {
    if (val) {
      init();
      if (formData.organizationCode) handChange(formData.organizationCode);
    }
  }
);
const isEdit = computed(() => {
  return props.tempRow && props.tempRow.inspectNo;
});

const title = computed(() => {
  return isEdit.value ? '编辑' : '新增';
});

const formRef = ref();
const loading = ref(false);
const formData = reactive({
  inspectNo: '',
  organizationCode: '',
  dischargeYear: '',
  organizationBoundary: [] as string[]
});

async function init() {
  if (props.tempRow && props.tempRow.inspectNo) {
    formData.inspectNo = props.tempRow.inspectNo;
    formData.organizationCode = props.tempRow.organizationCode;
    formData.dischargeYear = props.tempRow.dischargeYear;
    formData.organizationBoundary = props.tempRow.organizationBoundary;
  } else {
    formData.inspectNo = '';
    formData.organizationCode = '';
    formData.dischargeYear = '';
    formData.organizationBoundary = [];
  }
}

function handleConfirm() {
  formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      try {
        const params = {
          ...formData
        };
        console.log('handleConfirm params', params);
        loading.value = true;
        if (isEdit.value) {
          await postEditCarbonInspect(params);
          createMessage.success('编辑核查记录成功！');
        } else {
          await postCreateCarbonInspect(params);
          createMessage.success('新增核查记录成功！');
        }
        loading.value = false;
        emits('refresh');
        handleClose();
      } catch (error) {
        loading.value = false;
        console.log('error', error);
      }
    }
  });
}

// eslint-disable-next-line no-undef
const organizationBoundarOptions = ref<LabelValueOptions>([]);
async function handChange(v: string) {
  formData.organizationBoundary = [];
  try {
    const res = await getChildFactoryOrg(v);
    organizationBoundarOptions.value = res.map(item => {
      return {
        label: item.orgName,
        value: item.orgCode
      };
    });
  } catch (error) {
    console.log('error', error);
    organizationBoundarOptions.value = [];
  }
}

function handleClose() {
  dialogVisible.value = false;
}
</script>
